package com.durian.ierceptor;


import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.durian.config.ServiceException;
import com.durian.domain.entity.ObsUser;
import com.durian.service.IObsUserService;
import com.durian.utils.JwtUtils;
import io.jsonwebtoken.Claims;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;


public class JwtInterceptor implements HandlerInterceptor {

    @Autowired
    private IObsUserService userService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        String token = request.getHeader("Authorization");
        //如果不是映射到方法直接通过
        if (!(handler instanceof HandlerMethod)) {
            return true;
        }

        //执行认证
        if (StringUtils.isBlank(token)) {
            throw new ServiceException("无token,请重新登录", HttpStatus.UNAUTHORIZED.value());
        }

        Claims claims = JwtUtils.getClaimsByToken(token);

        if (JwtUtils.isTokenExpired(claims)) {
            throw new ServiceException("token已过期,请重新登录", HttpStatus.UNAUTHORIZED.value());
        }

        //获取token中的 user id
        Long userId = Long.parseLong(claims.getId());
        //根据token中的 userid 查询数据库
        ObsUser user = userService.getById(userId);
        if (ObjectUtils.isNull(user)) {
            throw new ServiceException("用户不存在,请重新登录", HttpStatus.UNAUTHORIZED.value());
        }

        return true;
    }
}

